package com.wrl.mmall.controller.portal;

import com.wrl.mmall.common.Const;
import com.wrl.mmall.common.ResponseCode;
import com.wrl.mmall.common.ServerResponse;
import com.wrl.mmall.pojo.User;
import com.wrl.mmall.service.IUserService;
import com.wrl.mmall.util.CookieUtil;
import com.wrl.mmall.util.JsonUtil;
import com.wrl.mmall.util.RedisShardedPoolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * user的管理
 * Created by Wang Renlei on 2018/8/22.
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService iUserService;

    //登陆
    @RequestMapping(value = "login.do")
    public ServerResponse<User> login(String username, String password, HttpSession session, HttpServletResponse response) {
        log.info("UserController.login");
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return ServerResponse.createByErrorMessage("必要参数为空");
        }
        ServerResponse<User> userData = iUserService.login(username, password);
        if (userData.isSuccess()) {
            //写入cookie
            CookieUtil.writeLoginToken(response, session.getId());
            RedisShardedPoolUtil.setEx(session.getId(), JsonUtil.objToString(userData.getData()), Const.RedisCacheExtime.REDIS_SESSION_EXTIME);
        }
        return userData;
    }

    //退出登录
    @RequestMapping(value = "login_out.do", method = RequestMethod.POST)
    public ServerResponse<User> loginOut(HttpServletRequest httpServletRequest, HttpServletResponse response) {
        log.info("UserController.loginOut");
        String loginToken = CookieUtil.readLoginToken(httpServletRequest);
        if (StringUtils.isEmpty(loginToken)) {
            return ServerResponse.createByErrorMessage("用户未登录，无法获取信息");
        }
        //删除cookie
        CookieUtil.delLoginToken(httpServletRequest, response);
        //删除redis的key
        RedisShardedPoolUtil.del(loginToken);
        return ServerResponse.createBySuccess();
    }

    //注册
    @RequestMapping(value = "register.do", method = RequestMethod.POST)
    public ServerResponse<String> registerUser(User user) {
        log.info("UserController.registerUser");
        if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword()) || StringUtils.isBlank(user.getEmail())) {
            return ServerResponse.createByErrorMessage("必要参数为空");
        }
        return iUserService.registerUser(user);
    }

    //注册校验
    @RequestMapping(value = "check_valid.do", method = RequestMethod.POST)
    public ServerResponse<String> checkValid(String str, String type) {
        log.info("UserController.checkValid");
        if (StringUtils.isBlank(str) || StringUtils.isBlank(type)) {
            return ServerResponse.createByErrorMessage("必要参数为空");
        }
        return iUserService.checkValid(str, type);
    }

    //获取用户信息
    @RequestMapping(value = "get_user_info.do", method = RequestMethod.POST)
    public ServerResponse<User> getUserInfo(HttpServletRequest httpServletRequest) {
        log.info("UserController.getUserInfo");
        String loginToken = CookieUtil.readLoginToken(httpServletRequest);
        if (StringUtils.isEmpty(loginToken)) {
            return ServerResponse.createByErrorMessage("用户未登录，无法获取信息");
        }
        String userStr = RedisShardedPoolUtil.get(loginToken);
        User user = JsonUtil.stringToObj(userStr, User.class);
        if (user != null) {
            return ServerResponse.createBySuccess(user);
        }
        return ServerResponse.createByErrorMessage("用户未登录，无法获取信息");
    }

    //返回密码提示问题
    @RequestMapping(value = "forget_get_question.do", method = RequestMethod.POST)
    public ServerResponse<String> forgetGetQuestion(String username) {
        log.info("UserController.forgetGetQuestion");
        if (StringUtils.isBlank(username)) {
            return ServerResponse.createByErrorMessage("必要参数为空");
        }
        return iUserService.selectQuestion(username);
    }

    //提交问题，获取token（后台返回前台一个token）
    @ResponseBody
    @RequestMapping(value = "commit_check_answer.do", method = RequestMethod.POST)
    public ServerResponse<String> forgetCheckAnswer(String username, String question, String answer) {
        log.info("UserController.forgetCheckAnswer");
        if (StringUtils.isBlank(username) || StringUtils.isBlank(question) || StringUtils.isBlank(answer)) {
            return ServerResponse.createByErrorMessage("必要参数为空");
        }
        return iUserService.forgetCheckAnswer(username, question, answer);
    }

    //重置密码（需要token）
    @RequestMapping(value = "forget_reset_password.do", method = RequestMethod.POST)
    public ServerResponse<String> forgetResetPassword(String username, String passwordNew, String token) {
        log.info("UserController.forgetResetPassword");
        if (StringUtils.isBlank(passwordNew)) {
            return ServerResponse.createByErrorMessage("必要参数为空");
        }
        return iUserService.forgetResetPassword(username, passwordNew, token);
    }

    //登陆状态重置密码
    @RequestMapping(value = "reset_password.do", method = RequestMethod.POST)
    public ServerResponse<String> resetPassword(HttpServletRequest httpServletRequest, String passwordOld, String passwordNew) {
        log.info("UserController.resetPassword");
        if (StringUtils.isBlank(passwordOld) || StringUtils.isBlank(passwordNew)) {
            return ServerResponse.createByErrorMessage("必要参数为空");
        }
        String loginToken = CookieUtil.readLoginToken(httpServletRequest);
        if (StringUtils.isEmpty(loginToken)) {
            return ServerResponse.createByErrorMessage("用户未登录，无法获取信息");
        }
        String userStr = RedisShardedPoolUtil.get(loginToken);
        User user = JsonUtil.stringToObj(userStr, User.class);
        if (user == null) {
            return ServerResponse.createByErrorMessage("用户未登录");
        }
        return iUserService.resetPassword(passwordOld, passwordNew, user);
    }

    //更新个人信息。需要session和新的用户信息
    @RequestMapping(value = "update_user_info.do", method = RequestMethod.POST)
    public ServerResponse<User> updateUserInfo(HttpServletRequest httpServletRequest, User user) {
        log.info("UserController.updateUserInfo");

        //获取当前登陆的用户
        String loginToken = CookieUtil.readLoginToken(httpServletRequest);
        if (StringUtils.isEmpty(loginToken)) {
            return ServerResponse.createByErrorMessage("用户未登录，无法获取信息");
        }
        String userStr = RedisShardedPoolUtil.get(loginToken);
        User currentUser = JsonUtil.stringToObj(userStr, User.class);
        if (currentUser == null) {
            return ServerResponse.createByErrorMessage("用户未登录");
        }
        //防止越权，设置参数user的id为当前登陆的用户id
        //这两个属性也是不可修改的
        user.setId(currentUser.getId());
        user.setUsername(currentUser.getUsername());

        ServerResponse<User> response = iUserService.updateUserInfo(user);
        if (response.isSuccess()) {
            //这里接受的response是修改成功后的数据，username是空的，所以要赋值成当前登陆用户的值
            response.getData().setUsername(currentUser.getUsername());
            //替换session里面，当前登陆用户的各属性
            RedisShardedPoolUtil.setEx(loginToken, JsonUtil.objToString(response.getData()), Const.RedisCacheExtime.REDIS_SESSION_EXTIME);
        }
        return response;
    }

    //获取用户的详细信息，并强制登陆
    @RequestMapping(value = "get_user_information.do", method = RequestMethod.POST)
    public ServerResponse<User> getUserInformation(HttpServletRequest httpServletRequest) {
        log.info("UserController.getUserInformation");
        String loginToken = CookieUtil.readLoginToken(httpServletRequest);
        if (StringUtils.isEmpty(loginToken)) {
            return ServerResponse.createByErrorMessage("用户未登录，无法获取信息");
        }
        String userStr = RedisShardedPoolUtil.get(loginToken);
        User user = JsonUtil.stringToObj(userStr, User.class);
        if (user == null) {
            return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "未登录，需要强制登录status=10");
        }
        return iUserService.getUserInformation(user.getId());
    }


}
